package com.shengyijie.adapter.asyncimageadapter;

import java.io.File;
import java.io.FileInputStream;
import java.lang.ref.SoftReference;

import java.util.HashMap; 
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;

public class AsyncImageLoaderFromFile {

	 private HashMap<String, SoftReference<Drawable>> imageCache;
	  public AsyncImageLoaderFromFile() {
	    	 imageCache = new HashMap<String, SoftReference<Drawable>>();
	     }
	  
	     public Drawable loadDrawable(final String imageUrl, final ImageCallbackFromFile imageCallback ) {
	         if (imageCache.containsKey(imageUrl)) {
	             SoftReference<Drawable> softReference = imageCache.get(imageUrl);
	             Drawable drawable = softReference.get();
	             if (drawable != null) {
	                 return drawable;
	             }
	         }
	         final Handler handler = new Handler() {
	             public void handleMessage(Message message) {
	                 imageCallback.imageLoaded((Drawable) message.obj, imageUrl);
	             }
	         };
	         new Thread() {
	             @Override
	             public void run() {
	                 Drawable drawable = loadImageFromUrl(imageUrl);
	                 imageCache.put(imageUrl, new SoftReference<Drawable>(drawable));
	                 Message message = handler.obtainMessage(0, drawable);
	                 handler.sendMessage(message);
	             }
	         }.start();
	         return null;
	     }
	  
	public static Drawable loadImageFromUrl(String url) {
		Drawable d = null;
		try {
			try {
			   File f = new File(Environment.getExternalStorageDirectory(),"diipo/"+url);
			   FileInputStream is = null;
			   is = new FileInputStream(f);
			   Bitmap bm;
			   bm = BitmapFactory.decodeStream(is, null, null);
			   d = new BitmapDrawable(bm);
			}catch (Exception e) {}
			 
			if (d == null) {
//				Resources res = PopularActivity.context.getResources();
//				d = res.getDrawable(R.drawable.image_loading);
			}
			
		} catch (Exception e) {
			if (d == null) {
//				Resources res = PopularActivity.context.getResources();
//				d = res.getDrawable(R.drawable.image_loading);
			}
		}
		return d;
	}
	  
	     public interface ImageCallbackFromFile {
	         public void imageLoaded(Drawable imageDrawable, String imageUrl);
	     }
	     
	     
	    

}
